<template>
	<view class="container">
		<!-- 页面头部 -->
		<view class="header">
			<view class="title">考试中心</view>
			<view class="subtitle">提升您的裁判技能水平</view>
		</view>
		
		<!-- 考试类型选择 -->
		<view class="exam-types">
			<view 
				class="type-item" 
				v-for="(item, index) in examTypes" 
				:key="index"
				:class="{active: currentType === index}"
				@click="switchType(index)"
			>
				<text>{{item}}</text>
			</view>
		</view>
		
		<!-- 考试列表 -->
		<scroll-view scroll-y class="exam-list-scroll">
			<view class="exam-list">
				<view class="exam-box" v-for="(item, index) in examList" :key="index">
					<!-- 考试项目卡片 -->
					<view class="exam-item" @click="toggleExamDetail(item._id || index)">
						<view class="exam-info">
							<text class="exam-title">{{item.title || '未知考试'}}</text>
							<text class="exam-desc">{{item.description || '暂无描述'}}</text>
							<view class="exam-meta">
								<view class="meta-item">
									<text class="meta-icon">⏱️</text>
									<text class="meta-text">{{item.duration || 0}}分钟</text>
								</view>
								<view class="meta-item">
									<text class="meta-icon">📝</text>
									<text class="meta-text">{{item.question_count || 0}}题</text>
								</view>
								<view class="meta-item">
									<text class="meta-icon">🏆</text>
									<text class="meta-text">{{item.pass_score || 0}}分通过</text>
								</view>
							</view>
						</view>
						<view class="exam-status" :class="{
							'status-available': item.status === 'available', 
							'status-completed': item.status === 'completed',
							'status-expired': item.status === 'expired'
						}">
							<text>{{getStatusText(item.status)}}</text>
						</view>
					</view>
					
					<!-- 展开的考试详情部分 -->
					<view class="exam-detail" v-if="expandedExamId === (item._id || index)" :class="{'sliding-down': isAnimating}">
						<view class="detail-content">
							<view class="detail-item">
								<text class="detail-label">考试说明：</text>
								<text class="detail-value">{{item.description || '暂无说明'}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">考试时长：</text>
								<text class="detail-value">{{(item.duration || 0)}}分钟</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">题目数量：</text>
								<text class="detail-value">{{(item.question_count || 0)}}题</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">通过分数：</text>
								<text class="detail-value">{{(item.pass_score || 0)}}分</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">考试规则：</text>
								<text class="detail-value">{{item.rules || '1. 考试过程中请勿切换页面或退出应用\n2. 考试时间结束后将自动提交\n3. 提交后系统将立即评分并显示结果'}}</text>
							</view>
							<view class="detail-action">
								<button class="btn-start" @click="startExam(item)">{{item.status === 'completed' ? '查看结果' : '开始考试'}}</button>
							</view>
						</view>
					</view>
				</view>
				
				<view v-if="examList.length === 0" class="empty-tip">
					<text>暂无考试内容</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { getToken, syncTokenStorage } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				examTypes: ['全部考试', '规则考试', '实战考试', '认证考试'],
				currentType: 0,
				examList: [],
				expandedExamId: null, // 当前展开的考试ID
				isAnimating: false    // 是否正在执行动画
			}
		},
		onLoad() {
			// 同步token存储
			syncTokenStorage();
			// 获取考试列表
			this.getExamList();
		},
		onShow() {
			console.log('考试页面显示，检查是否需要刷新');
			// 检查是否需要刷新
			const needRefresh = uni.getStorageSync('exam_list_need_refresh');
			if (needRefresh) {
				console.log('检测到考试完成标记，刷新列表');
				// 清除标记
				uni.removeStorageSync('exam_list_need_refresh');
				// 重新获取考试列表
				this.getExamList();
			}
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.refreshExamList();
		},
		methods: {
			// 下拉刷新考试列表
			async refreshExamList() {
				console.log('开始下拉刷新考试列表');
				
				try {
					// 重新获取考试列表
					await this.getExamList();
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					});
				} catch (error) {
					console.error('刷新考试列表失败', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					});
				} finally {
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
				}
			},
			
			// 切换考试类型
			switchType(index) {
				this.currentType = index;
				this.expandedExamId = null; // 切换类型时关闭已展开的详情
				this.getExamList();
			},
			
			// 获取考试列表
			async getExamList() {
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					// 1. 从云端获取考试列表
					const examList = await this.fetchExamListFromCloud();
					
					// 2. 从云端获取用户考试记录
					const examRecords = await this.getUserExamRecordsFromCloud();
					
					// 3. 合并考试列表和考试记录状态
					this.mergeExamListWithRecords(examList, examRecords);
					
					// 4. 将合并后的数据更新至本地缓存(轻量级缓存)
					uni.setStorageSync('cached_exam_statuses', JSON.stringify({
						timestamp: Date.now(),
						examStatuses: this.createExamStatusMap()
					}));
					
					// 清除刷新标记
					uni.removeStorageSync('exam_list_need_refresh');
				} catch (error) {
					console.error('获取考试数据失败', error);
					
					// 5. 错误处理：尝试从本地缓存获取
					try {
						const cachedDataStr = uni.getStorageSync('cached_exam_statuses');
						if (cachedDataStr) {
							const cachedData = JSON.parse(cachedDataStr);
							this.handleCachedData(cachedData);
							uni.showToast({
								title: '使用缓存数据，请检查网络连接',
								icon: 'none'
							});
						} else {
							this.getMockExamList();
						}
					} catch (e) {
						console.error('解析缓存数据失败', e);
						this.getMockExamList();
					}
				} finally {
					uni.hideLoading();
				}
			},
			
			// 从云端获取考试列表
			async fetchExamListFromCloud() {
				try {
					const type = this.currentType === 0 ? '' : this.examTypes[this.currentType];
					// 使用tokenManager获取token
					const token = getToken();
					
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.getExamList({ 
						type, 
						token 
					});
					
					if (res.code === 0) {
						return res.data || [];
							} else {
						throw new Error(res.message || '获取考试列表失败');
							}
				} catch (error) {
					throw error;
				}
			},
			
			// 从云端获取用户考试记录
			async getUserExamRecordsFromCloud() {
				try {
					// 使用tokenManager获取token
					const token = getToken();
					const userInfoStr = uni.getStorageSync('userInfo');
					
					// 判断用户信息是否存在
					if (!token || !userInfoStr) {
						console.log('用户未登录，跳过获取考试记录');
						return [];
					}
					
						// 解析用户信息
						const userInfo = JSON.parse(userInfoStr);
						console.log('获取考试记录，用户ID:', userInfo._id);
						
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.getExamRecords({
								page: 1,
								pageSize: 100,
								token,
								userInfo: userInfo // 直接传递完整用户信息对象
					});
					
					console.log('获取考试记录响应:', res);
					if (res.code === 0 && res.data) {
						const records = res.data.list || [];
									console.log('成功获取考试记录数量:', records.length);
						
						// 过滤出已完成的考试记录
						const completedRecords = records.filter(record => 
							record.status === 'completed' || 
							record.submit_time // 如果有提交时间，也认为是已完成
						);
						console.log('已完成的考试记录数量:', completedRecords.length);
						
						return completedRecords;
								} else {
						console.warn('获取考试记录失败:', res.message);
						return [];
							}
				} catch (error) {
					console.error('获取考试记录失败', error);
					return [];
					}
			},
			
			// 合并考试列表和考试记录
			mergeExamListWithRecords(examList, records) {
				if (!records || records.length === 0) {
					console.log('没有获取到考试记录');
					this.examList = examList;
					return;
				}
				
				console.log('获取到考试记录数量:', records.length);
				
				// 创建考试记录映射 - 确保使用字符串ID进行比较
				const recordMap = {};
				records.forEach(record => {
					if (record.exam_id) {
						// 确保转换成字符串进行比较
						const examIdStr = record.exam_id.toString();
						console.log('记录考试ID:', examIdStr);
						recordMap[examIdStr] = record;
					}
				});
				
				console.log('考试记录ID列表:', Object.keys(recordMap));
				
				// 合并考试状态
				this.examList = examList.map(exam => {
					// 确保转换成字符串进行比较
					const examIdStr = exam._id.toString();
					console.log('处理考试ID:', examIdStr);
					
					const record = recordMap[examIdStr];
					const result = {
						...exam,
						status: exam.status || 'available'
					};
					
					if (record) {
						console.log('找到匹配记录，更新状态为已完成:', examIdStr);
						result.status = 'completed';
						result.score = record.score || 0;
						result.submit_time = record.submit_time;
						result.recordId = record._id; // 保存考试记录ID，用于查看结果
					} else {
						console.log('未找到匹配记录:', examIdStr);
					}
					
					return result;
				});
				
				// 排序（最新的在前面）
				this.examList.sort((a, b) => {
					// 优先按提交时间排序
					if (a.submit_time && b.submit_time) {
						return new Date(b.submit_time) - new Date(a.submit_time);
					}
					// 其次按创建时间排序
					return b.create_time - a.create_time;
				});
				
				// 输出合并后状态统计
				const statusStats = this.examList.reduce((acc, exam) => {
					acc[exam.status] = (acc[exam.status] || 0) + 1;
					return acc;
				}, {});
				console.log('合并后状态统计:', statusStats);
			},
			
			// 创建考试状态映射用于本地缓存
			createExamStatusMap() {
				const statusMap = {};
				this.examList.forEach(exam => {
					statusMap[exam._id] = {
						status: exam.status || 'available',
						score: exam.score || 0,
						timestamp: Date.now()
					};
				});
				return statusMap;
			},
			
			// 处理缓存数据（当网络请求失败时）
			handleCachedData(cachedData) {
				// 检查缓存是否过期（1小时）
				const isExpired = Date.now() - cachedData.timestamp > 3600000;
				
				if (isExpired) {
					console.log('缓存数据已过期');
					this.getMockExamList();
					return;
				}
				
				// 使用缓存的考试状态
				if (this.examList.length > 0 && cachedData.examStatuses) {
					this.examList = this.examList.map(exam => {
						const cachedStatus = cachedData.examStatuses[exam._id];
						if (cachedStatus) {
							exam.status = cachedStatus.status;
							exam.score = cachedStatus.score;
						}
						return exam;
					});
				} else {
					this.getMockExamList();
				}
			},
			
			// 获取模拟考试列表
			getMockExamList() {
				// 模拟数据
				const allExams = [
					{
						_id: '1',
						title: '足球比赛规则基础考试',
						description: '测试您对足球比赛基本规则的掌握程度',
						duration: 30,
						question_count: 20,
						pass_score: 80,
						type: '规则考试',
						status: 'available',
						create_time: new Date('2023-01-01').getTime()
					},
					{
						_id: '2',
						title: '裁判手势与信号实战考试',
						description: '测试您对裁判手势与信号的理解和应用能力',
						duration: 45,
						question_count: 30,
						pass_score: 85,
						type: '实战考试',
						status: 'available',
						create_time: new Date('2023-01-15').getTime()
					},
					{
						_id: '3',
						title: '国际足联裁判认证考试',
						description: '国际足联裁判认证资格考试，通过后可获得认证证书',
						duration: 60,
						question_count: 50,
						pass_score: 90,
						type: '认证考试',
						status: 'available',
						create_time: new Date('2023-02-01').getTime()
					},
					{
						_id: '4',
						title: '2023年度裁判规则更新考试',
						description: '测试您对2023年新修订的足球比赛规则的掌握情况',
						duration: 40,
						question_count: 25,
						pass_score: 85,
						type: '规则考试',
						status: 'completed',
						score: 92,
						create_time: new Date('2023-03-01').getTime()
					}
				];
				
				// 根据类型筛选
				if (this.currentType !== 0) {
					const type = this.examTypes[this.currentType];
					this.examList = allExams.filter(item => item.type === type);
				} else {
					this.examList = allExams;
				}
				
				// 按创建时间排序（最新的在前面）
				this.examList.sort((a, b) => b.create_time - a.create_time);
				console.log('已加载模拟数据');
			},
			
			// 切换考试详情展开状态
			toggleExamDetail(examId) {
				if (this.expandedExamId === examId) {
					// 如果点击的是已展开的考试，则收起
					this.expandedExamId = null;
				} else {
					// 否则展开点击的考试
					this.expandedExamId = examId;
					
					// 添加动画效果
					this.isAnimating = true;
					setTimeout(() => {
						this.isAnimating = false;
					}, 300);
					
					// 滚动到展开的项目
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.exam-box').boundingClientRect(data => {
							uni.pageScrollTo({
								scrollTop: data.top,
								duration: 300
							});
						}).exec();
					});
				}
			},
			
			// 开始考试
			startExam(exam) {
				// 检查登录状态
				const token = getToken();
				const userInfoStr = uni.getStorageSync('userInfo');
				
				// 验证登录状态
				if (!token || !userInfoStr) {
					uni.showModal({
						title: '提示',
						content: '请先登录后再参加考试',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login?from=' + encodeURIComponent('/pages/exam/exam')
								});
							}
						}
					});
					return;
				}
				
				// 验证用户信息完整性
				try {
					const userInfo = JSON.parse(userInfoStr);
					if (!userInfo._id || !userInfo.nickname) {
						uni.showModal({
							title: '提示',
							content: '您的个人信息不完整，请先完善个人资料',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/my/profile'
									});
								}
							}
						});
						return;
					}
					
					// 验证通过，继续执行原有逻辑
					if (!exam) {
						uni.showToast({
							title: '考试数据不完整',
							icon: 'none'
						});
						return;
					}
					
					const examId = exam._id || '';
					if (!examId) {
						uni.showToast({
							title: '考试ID不存在',
							icon: 'none'
						});
						return;
					}
					
					// 如果考试已完成，则查看考试结果
					if (exam.status === 'completed') {
						// 使用recordId（如果有）或者examId跳转到结果页面
						const recordId = exam.recordId || '';
						const params = recordId ? 
							`recordId=${recordId}&examId=${examId}` : 
							`examId=${examId}`;
						
						uni.navigateTo({
							url: `/packageExam/exam/exam-result?${params}`
						});
						return;
					}
					
					// 否则开始新考试
					uni.navigateTo({
						url: `/packageExam/exam/exam-page?id=${examId}`
					});
				} catch (e) {
					console.error('解析用户信息出错', e);
					uni.showToast({
						title: '用户信息异常，请重新登录',
						icon: 'none'
					});
				}
			},
			
			// 获取状态文本
			getStatusText(status) {
				switch(status) {
					case 'available':
						return '可参加';
					case 'completed':
						return '已完成';
					case 'expired':
						return '已过期';
					default:
						return '可参加';
				}
			}
		}
	}
</script>

<style>
	.container {
		background-color: #F8F8F8;
		min-height: 100vh;
	}
	
	/* 头部样式 */
	.header {
		background-color: #1BAE76;
		padding: 40rpx 30rpx;
		color: #FFFFFF;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.subtitle {
		font-size: 26rpx;
	}
	
	/* 考试类型选择 */
	.exam-types {
		display: flex;
		background-color: #FFFFFF;
		padding: 20rpx 0;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}
	
	.type-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666666;
		padding: 15rpx 0;
		position: relative;
	}
	
	.type-item.active {
		color: #1BAE76;
		font-weight: bold;
	}
	
	.type-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 80rpx;
		height: 6rpx;
		background-color: #1BAE76;
		border-radius: 6rpx;
	}
	
	/* 考试列表 */
	.exam-list-scroll {
		height: calc(100vh - 200rpx);
	}
	
	.exam-list {
		padding: 20rpx;
	}
	
	.exam-box {
		margin-bottom: 20rpx;
	}
	
	.exam-item {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		display: flex;
		justify-content: space-between;
		position: relative;
	}
	
	.exam-info {
		flex: 1;
		margin-right: 20rpx;
		display: flex;
		flex-direction: column;
	}
	
	.exam-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
		line-height: 1.4;
	}
	
	.exam-desc {
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 15rpx;
		line-height: 1.5;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}
	
	.exam-meta {
		display: flex;
		flex-wrap: wrap;
	}
	
	.meta-item {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
		margin-bottom: 10rpx;
	}
	
	.meta-icon {
		font-size: 28rpx;
		margin-right: 8rpx;
	}
	
	.meta-text {
		font-size: 24rpx;
		color: #666666;
	}
	
	.exam-status {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		height: 36rpx;
		white-space: nowrap;
	}
	
	.status-available {
		background-color: rgba(27, 174, 118, 0.1);
		color: #1BAE76;
	}
	
	.status-completed {
		background-color: rgba(155, 155, 155, 0.1);
		color: #999999;
	}
	
	.status-expired {
		background-color: rgba(230, 162, 60, 0.1);
		color: #E6A23C;
	}
	
	/* 展开详情样式 */
	.exam-detail {
		background-color: #F5F5F5;
		border-radius: 0 0 12rpx 12rpx;
		margin-top: -20rpx;
		overflow: hidden;
		transition: all 0.3s;
	}
	
	.detail-content {
		padding: 30rpx;
	}
	
	.detail-item {
		margin-bottom: 20rpx;
	}
	
	.detail-label {
		font-size: 28rpx;
		color: #333333;
		font-weight: bold;
		margin-bottom: 8rpx;
		display: block;
	}
	
	.detail-value {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.6;
	}
	
	.detail-action {
		margin-top: 30rpx;
	}
	
	.btn-start {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #1BAE76;
		color: #FFFFFF;
		font-size: 30rpx;
		font-weight: bold;
		border-radius: 8rpx;
	}
	
	/* 滑动动画 */
	.sliding-down {
		animation: slideDown 0.3s ease-in-out;
	}
	
	@keyframes slideDown {
		from { 
			opacity: 0;
			transform: translateY(-20rpx);
		}
		to { 
			opacity: 1;
			transform: translateY(0);
		}
	}
	
	/* 空列表提示 */
	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999999;
		font-size: 28rpx;
	}
</style> 